package com.myphoto.base.log.appender;

import com.myphoto.base.config.properties.IConfig;
import com.myphoto.base.util.SpringContextUtils;
import com.myphoto.base.log.service.LogService;
import com.p6spy.engine.logging.Category;
import com.p6spy.engine.spy.appender.FormattedLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class P6SpyDbLogger extends FormattedLogger {

    private Logger log = LoggerFactory.getLogger("p6spy");

    public P6SpyDbLogger() {
    }

    public void logException(Exception e) {
        this.log.info("", e);
    }

    public void logText(String text) {
        this.log.info(text);
    }

    public void logSQL(int connectionId, String now, long elapsed, Category category, String prepared, String sql, String url) {
        String msg = this.strategy.formatMessage(connectionId, now, elapsed, category.toString(), prepared, sql, url);
        try{
            //排除性能监控表相关语句
            if(msg.toLowerCase().indexOf("tb_log_p6spy")>=0){
                return;
            }
            IConfig mesvmConfig = SpringContextUtils.getBean(IConfig.class);
            boolean p6spy_record_enable = Boolean.parseBoolean(mesvmConfig.getConfig().getP6spy_record_enable());
            if(p6spy_record_enable){
                //将p6spy日志写到数据库
                LogService logService = SpringContextUtils.getBean(LogService.class);
                logService.writeDB(msg);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public boolean isCategoryEnabled(Category category) {
        if (Category.ERROR.equals(category)) {
            return this.log.isErrorEnabled();
        } else if (Category.WARN.equals(category)) {
            return this.log.isWarnEnabled();
        } else {
            return Category.DEBUG.equals(category) ? this.log.isDebugEnabled() : this.log.isInfoEnabled();
        }
    }
}
